<template>
  <div class="api-docs-view">
    <h1 class="page-title">开发者API文档</h1>
    <p class="page-description">本文档提供全同态加密库的API使用指南，帮助开发者在自己的应用中集成隐私计算功能。</p>
    
    <div class="docs-container">
      <!-- 左侧导航栏 -->
      <div class="docs-sidebar">
        <div class="search-box">
          <input 
            type="text" 
            v-model="searchQuery" 
            placeholder="搜索API..."
            @input="filterApiList"
          />
        </div>
        
        <div class="sidebar-section">
          <div class="section-title">入门指南</div>
          <ul class="section-links">
            <li>
              <a href="#getting-started" @click.prevent="scrollToSection('getting-started')" :class="{ active: activeSection === 'getting-started' }">快速开始</a>
            </li>
            <li>
              <a href="#installation" @click.prevent="scrollToSection('installation')" :class="{ active: activeSection === 'installation' }">安装指南</a>
            </li>
            <li>
              <a href="#basic-concepts" @click.prevent="scrollToSection('basic-concepts')" :class="{ active: activeSection === 'basic-concepts' }">基本概念</a>
            </li>
          </ul>
        </div>
        
        <div class="sidebar-section">
          <div class="section-title">核心API</div>
          <ul class="section-links">
            <li v-for="api in filteredApiList" :key="api.id">
              <a :href="'#' + api.id" @click.prevent="scrollToSection(api.id)" :class="{ active: activeSection === api.id }">{{ api.name }}</a>
            </li>
          </ul>
        </div>
        
        <div class="sidebar-section">
          <div class="section-title">示例代码</div>
          <ul class="section-links">
            <li>
              <a href="#example-comparison" @click.prevent="scrollToSection('example-comparison')" :class="{ active: activeSection === 'example-comparison' }">加密比较</a>
            </li>
            <li>
              <a href="#example-addition" @click.prevent="scrollToSection('example-addition')" :class="{ active: activeSection === 'example-addition' }">加密加法</a>
            </li>
            <li>
              <a href="#example-advanced" @click.prevent="scrollToSection('example-advanced')" :class="{ active: activeSection === 'example-advanced' }">高级操作</a>
            </li>
          </ul>
        </div>
      </div>
      
      <!-- 中间内容区 -->
      <div class="docs-content" ref="docsContent" @scroll="handleScroll">
        <!-- 快速开始部分 -->
        <section id="getting-started" class="content-section">
          <h2>快速开始</h2>
          <p>FHE Privacy Guard 提供了简单易用的API，帮助开发者快速集成全同态加密功能。以下是一个基本的使用流程：</p>
          
          <div class="steps-container">
            <div class="step-item">
              <div class="step-number">1</div>
              <div class="step-content">
                <h3>安装依赖</h3>
                <p>安装TenSEAL库和Flask</p>
                <pre><code>pip install tenseal flask flask-cors</code></pre>
              </div>
            </div>
            
            <div class="step-item">
              <div class="step-number">2</div>
              <div class="step-content">
                <h3>初始化参数</h3>
                <p>设置BFV加密参数</p>
                <pre><code>import tenseal as ts

        # 创建BFV加密上下文
        def create_context():
            poly_modulus_degree = 4096
            plain_modulus = 40961  # 支持批处理的明文模数
            
            context = ts.context(ts.SCHEME_TYPE.BFV, poly_modulus_degree, plain_modulus)
            context.generate_galois_keys()
            
            return context</code></pre>
              </div>
            </div>
            
            <div class="step-item">
              <div class="step-number">3</div>
              <div class="step-content">
                <h3>创建会话</h3>
                <p>创建加密会话并获取会话ID</p>
                <pre><code>from flask import Flask, request, jsonify

        app = Flask(__name__)

        # 存储会话的字典
        sessions = {}

        @app.route('/api/create_session', methods=['POST'])
        def create_session():
            # 创建新的加密上下文
            context = create_context()
            
            # 生成会话ID
            session_id = os.urandom(16).hex()
            
            # 存储上下文
            sessions[session_id] = {
                'context': serialize_context(context)
            }
            
            return jsonify({
                'success': True,
                'session_id': session_id
            })</code></pre>
              </div>
            </div>
            
            <div class="step-item">
              <div class="step-number">4</div>
              <div class="step-content">
                <h3>加密数据</h3>
                <p>使用BFV方案加密整数数据</p>
                <pre><code>@app.route('/api/encrypt', methods=['POST'])
        def encrypt_data():
            data = request.json
            session_id = data.get('session_id')
            value_a = int(data.get('value_a'))
            value_b = int(data.get('value_b'))
            
            # 获取上下文
            context = deserialize_context(sessions[session_id]['context'])
            
            # 加密数值
            encrypted_a = ts.bfv_vector(context, [value_a])
            encrypted_b = ts.bfv_vector(context, [value_b])
            
            # 存储加密数据
            sessions[session_id]['encrypted_a'] = serialize_vector(encrypted_a)
            sessions[session_id]['encrypted_b'] = serialize_vector(encrypted_b)
            
            return jsonify({
                'success': True,
                'encrypted_a': sessions[session_id]['encrypted_a'][:50] + '...',
                'encrypted_b': sessions[session_id]['encrypted_b'][:50] + '...'
            })</code></pre>
              </div>
            </div>
            
            <div class="step-item">
              <div class="step-number">5</div>
              <div class="step-content">
                <h3>执行计算</h3>
                <p>在加密数据上执行操作</p>
                <pre><code>@app.route('/api/compute', methods=['POST'])
        def compute():
            data = request.json
            session_id = data.get('session_id')
            operation = data.get('operation')
            
            # 获取上下文和加密数据
            context = deserialize_context(sessions[session_id]['context'])
            encrypted_a = deserialize_vector(sessions[session_id]['encrypted_a'], context)
            encrypted_b = deserialize_vector(sessions[session_id]['encrypted_b'], context)
            
            if operation == 'add':
                # 加法操作
                encrypted_sum = encrypted_a + encrypted_b
                # 解密结果
                decrypted_result = encrypted_sum.decrypt()[0]
                
                return jsonify({
                    'success': True,
                    'result_type': '加法结果',
                    'result': decrypted_result,
                    'explanation': '两个加密数值的和'
                })</code></pre>
              </div>
            </div>
            
            <div class="step-item">
              <div class="step-number">6</div>
              <div class="step-content">
                <h3>验证结果</h3>
                <p>验证加密计算的结果</p>
                <pre><code>@app.route('/api/verify', methods=['POST'])
        def verify():
            data = request.json
            session_id = data.get('session_id')
            operation = data.get('operation')
            
            plain_a = sessions[session_id]['plain_a']
            plain_b = sessions[session_id]['plain_b']
            
            if operation == 'add':
                plaintext_result = plain_a + plain_b
            
            return jsonify({
                'success': True,
                'plaintext_result': plaintext_result,
                'match': True
            })</code></pre>
              </div>
            </div>
          </div>
        </section>
        
        <!-- 安装指南部分 -->
        <section id="installation" class="content-section">
          <h2>安装指南</h2>
          
          <div class="installation-options">
            <div class="install-card">
              <h3>安装TenSEAL库</h3>
              <pre><code>pip install tenseal</code></pre>
              <p>TenSEAL是微软SEAL库的Python封装，提供了全同态加密功能。</p>
            </div>
            
            <div class="install-card">
              <h3>安装Flask和CORS</h3>
              <pre><code>pip install flask flask-cors</code></pre>
              <p>用于构建API服务器和支持跨域请求。</p>
            </div>
            
            <div class="install-card">
              <h3>前端依赖</h3>
              <pre><code>npm install</code></pre>
              <p>安装Vue.js和其他前端依赖。</p>
            </div>
          </div>
          
          <div class="system-requirements">
            <h3>系统要求</h3>
            <ul>
              <li>Python 3.7+</li>
              <li>Node.js 14+</li>
              <li>C++17 兼容编译器（TenSEAL依赖）</li>
              <li>至少 4GB RAM</li>
            </ul>
            <p>注意：全同态加密操作计算密集，建议使用性能较好的硬件。</p>
          </div>
        </section>
        
        <!-- 基本概念部分 -->
        <section id="basic-concepts" class="content-section">
          <h2>基本概念</h2>
          
          <div class="concept-grid">
            <div class="concept-card">
              <h3>BFV加密方案</h3>
              <p>本项目使用BFV（Brakerski-Fan-Vercauteren）方案，它是一种基于格密码学的全同态加密方案，适用于整数运算，提供精确的结果。</p>
            </div>
            
            <div class="concept-card">
              <h3>加密参数</h3>
              <p>BFV方案的主要参数包括多项式阶数（poly_modulus_degree）和明文模数（plain_modulus）。本项目使用4096的多项式阶数和40961的明文模数，以支持批处理操作。</p>
            </div>
            
            <div class="concept-card">
              <h3>会话管理</h3>
              <p>系统使用会话ID来跟踪用户的加密上下文和数据，确保不同用户的数据相互隔离。会话信息存储在服务器内存中。</p>
            </div>
            
            <div class="concept-card">
              <h3>支持的操作</h3>
              <p>当前系统支持在加密数据上进行加法、平均值计算，以及模拟的比较操作（注意：全同态加密不直接支持比较操作）。</p>
            </div>
          </div>
          
          <div class="concept-diagram">
            <h3>FHE系统架构</h3>
            <img src="/src/assets/images/fhe-architecture.svg" alt="FHE系统架构图" class="architecture-diagram" />
            <p class="diagram-caption">图1：全同态加密系统的主要组件和数据流</p>
          </div>
        </section>
        
        <!-- API参考部分 -->
        <template v-for="api in apiList" :key="api.id">
          <section :id="api.id" class="content-section api-reference">
            <h2>{{ api.name }}</h2>
            <p>{{ api.description }}</p>
            
            <div class="api-details">
              <div class="code-example">
                <h3>示例用法</h3>
                <pre><code>{{ api.example }}</code></pre>
              </div>
              
              <div class="parameters-section">
                <h3>参数说明</h3>
                <table class="parameters-table">
                  <thead>
                    <tr>
                      <th>参数名</th>
                      <th>类型</th>
                      <th>默认值</th>
                      <th>说明</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="param in api.parameters" :key="param.name">
                      <td><code>{{ param.name }}</code></td>
                      <td>{{ param.type }}</td>
                      <td>{{ param.default || '-' }}</td>
                      <td>{{ param.description }}</td>
                    </tr>
                  </tbody>
                </table>
              </div>
              
              <div class="return-value">
                <h3>返回值</h3>
                <p><strong>类型：</strong> {{ api.returnType }}</p>
                <p>{{ api.returnDescription }}</p>
              </div>
              
              <div class="notes-section" v-if="api.notes">
                <h3>注意事项</h3>
                <ul>
                  <li v-for="(note, index) in api.notes" :key="index">{{ note }}</li>
                </ul>
              </div>
            </div>
          </section>
        </template>
        
        <!-- 示例代码部分 -->
        <section id="example-comparison" class="content-section">
          <h2>示例：加密比较</h2>
          
          <div class="example-description">
            <p>以下示例展示如何使用API进行加密数据比较。注意，全同态加密不直接支持比较操作，这里使用的是服务器端的模拟实现。</p>
          </div>
          
          <div class="code-example">
            <pre><code>// 创建会话
        async function createSession() {
          const response = await fetch('http://localhost:5000/api/create_session', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({})
          });
          
          const data = await response.json();
          return data.session_id;
        }

        // 加密数据
        async function encryptData(sessionId, valueA, valueB) {
          const response = await fetch('http://localhost:5000/api/encrypt', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              session_id: sessionId,
              value_a: valueA,
              value_b: valueB
            })
          });
          
          return await response.json();
        }

        // 执行比较操作
        async function compareEncryptedData(sessionId) {
          const response = await fetch('http://localhost:5000/api/compute', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              session_id: sessionId,
              operation: 'compare'
            })
          });
          
          return await response.json();
        }

        // 验证结果
        async function verifyResult(sessionId) {
          const response = await fetch('http://localhost:5000/api/verify', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              session_id: sessionId,
              operation: 'compare'
            })
          });
          
          return await response.json();
        }

        // 执行完整流程
        async function runComparisonDemo() {
          try {
            // 1. 创建会话
            const sessionId = await createSession();
            console.log('会话创建成功，ID:', sessionId);
            
            // 2. 加密数据
            const valueA = 3500;
            const valueB = 2800;
            const encryptResult = await encryptData(sessionId, valueA, valueB);
            console.log('数据加密成功');
            
            // 3. 执行比较
            const compareResult = await compareEncryptedData(sessionId);
            console.log('比较结果:', compareResult.result);
            console.log('说明:', compareResult.explanation);
            
            // 4. 验证结果
            const verifyData = await verifyResult(sessionId);
            console.log('明文结果:', verifyData.plaintext_result);
            console.log('结果匹配:', verifyData.match ? '是' : '否');
          } catch (error) {
            console.error('发生错误:', error);
          }
        }

        // 运行演示
        runComparisonDemo();</code></pre>
          </div>
          
          <div class="example-notes">
            <h3>说明</h3>
            <p>这个示例展示了如何使用API进行加密数据比较。在实际应用中，比较操作通常需要使用特殊的协议或多方计算技术。</p>
            <p>本演示中的比较操作是在服务器端模拟的，实际上是在明文上进行比较，仅用于演示目的。</p>
          </div>
        </section>

        <section id="example-addition" class="content-section">
          <h2>示例：加密加法</h2>
          
          <div class="example-description">
            <p>以下示例展示如何使用API对加密数据执行加法运算。加法是全同态加密支持的基本操作之一。</p>
          </div>
          
          <div class="code-example">
            <pre><code>// 创建会话和加密数据的函数与前面示例相同

        // 执行加法操作
        async function addEncryptedData(sessionId) {
          const response = await fetch('http://localhost:5000/api/compute', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              session_id: sessionId,
              operation: 'add'
            })
          });
          
          return await response.json();
        }

        // 执行完整流程
        async function runAdditionDemo() {
          try {
            // 1. 创建会话
            const sessionId = await createSession();
            console.log('会话创建成功，ID:', sessionId);
            
            // 2. 加密数据
            const valueA = 3500;
            const valueB = 2800;
            await encryptData(sessionId, valueA, valueB);
            console.log('数据加密成功');
            
            // 3. 执行加法
            const addResult = await addEncryptedData(sessionId);
            console.log('加法结果:', addResult.result);
            
            // 4. 验证结果
            const verifyData = await fetch('http://localhost:5000/api/verify', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
                session_id: sessionId,
                operation: 'add'
              })
            }).then(res => res.json());
            
            console.log('明文加法结果:', verifyData.plaintext_result);
            console.log('结果匹配:', verifyData.match ? '是' : '否');
            console.log('验证:', valueA + valueB === addResult.result ? '正确' : '错误');
          } catch (error) {
            console.error('发生错误:', error);
          }
        }

        // 运行演示
        runAdditionDemo();</code></pre>
          </div>
          
          <div class="example-notes">
            <h3>说明</h3>
            <p>加法是全同态加密中最基本和高效的操作。BFV方案提供精确的整数加法结果。</p>
            <p>在本示例中，加密加法的结果与明文加法完全一致，这展示了全同态加密的核心特性。</p>
          </div>
        </section>

        <section id="example-advanced" class="content-section">
          <h2>示例：平均值计算</h2>
          
          <div class="example-description">
            <p>以下示例展示如何使用API计算两个加密数值的平均值。</p>
          </div>
          
          <div class="code-example">
            <pre><code>// 创建会话和加密数据的函数与前面示例相同

        // 计算平均值
        async function calculateAverage(sessionId) {
          const response = await fetch('http://localhost:5000/api/compute', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              session_id: sessionId,
              operation: 'average'
            })
          });
          
          return await response.json();
        }

        // 执行完整流程
        async function runAverageDemo() {
          try {
            // 1. 创建会话
            const sessionId = await createSession();
            console.log('会话创建成功，ID:', sessionId);
            
            // 2. 加密数据
            const valueA = 3500;
            const valueB = 2800;
            await encryptData(sessionId, valueA, valueB);
            console.log('数据加密成功');
            
            // 3. 计算平均值
            const avgResult = await calculateAverage(sessionId);
            console.log('平均值结果:', avgResult.result);
            
            // 4. 验证结果
            const verifyData = await fetch('http://localhost:5000/api/verify', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
                session_id: sessionId,
                operation: 'average'
              })
            }).then(res => res.json());
            
            console.log('明文平均值:', verifyData.plaintext_result);
            console.log('结果匹配:', verifyData.match ? '是' : '否');
            console.log('验证:', (valueA + valueB) / 2 === avgResult.result ? '正确' : '错误');
          } catch (error) {
            console.error('发生错误:', error);
          }
        }

        // 运行演示
        runAverageDemo();</code></pre>
          </div>
          
          <div class="example-notes">
            <h3>说明</h3>
            <p>在当前实现中，平均值计算是通过先执行加密加法，然后在解密后除以2来实现的。</p>
            <p>全同态加密通常不直接支持除法操作，需要使用特殊技术或在解密后执行。</p>
            <p>在实际应用中，可以使用更复杂的技术来实现完全同态的平均值计算。</p>
          </div>
        </section>
      </div>
      
      <!-- 右侧参数说明区 -->
      <div class="docs-params" v-if="activeApi">
        <div class="params-header">
          <h3>{{ activeApi.name }}</h3>
          <button class="close-btn" @click="activeApi = null">×</button>
        </div>
        
        <div class="params-content">
          <div class="param-description">
            {{ activeApi.description }}
          </div>
          
          <div class="param-details" v-for="param in activeApi.parameters" :key="param.name">
            <div class="param-name"><code>{{ param.name }}</code></div>
            <div class="param-type">{{ param.type }}</div>
            <div class="param-info">
              <div v-if="param.default"><strong>默认值:</strong> {{ param.default }}</div>
              <div>{{ param.description }}</div>
            </div>
          </div>
          
          <div class="param-notes" v-if="activeApi.notes && activeApi.notes.length > 0">
            <h4>注意事项</h4>
            <ul>
              <li v-for="(note, index) in activeApi.notes" :key="index">{{ note }}</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';

// API列表数据
const apiList = [
  {
    id: 'create-session',
    name: 'create_session',
    description: '创建新的加密会话，生成加密上下文和会话ID。',
    example: 'fetch("http://localhost:5000/api/create_session", {\n  method: "POST",\n  headers: {\n    "Content-Type": "application/json"\n  },\n  body: JSON.stringify({})\n})\n.then(response => response.json())\n.then(data => {\n  if (data.success) {\n    console.log("会话ID:", data.session_id);\n  }\n});',
    parameters: [],
    returnType: 'JSON对象',
    returnDescription: '包含success状态和session_id',
    notes: [
      '每个会话都有独立的加密上下文和密钥',
      '会话信息存储在服务器内存中，服务器重启后会丢失',
      '实际应用中应实现更安全的会话管理机制'
    ]
  },
  {
    id: 'encrypt',
    name: 'encrypt',
    description: '加密两个整数值，并将加密结果存储在会话中。',
    example: 'fetch("http://localhost:5000/api/encrypt", {\n  method: "POST",\n  headers: {\n    "Content-Type": "application/json"\n  },\n  body: JSON.stringify({\n    session_id: "your_session_id",\n    value_a: 3500,\n    value_b: 2800\n  })\n})\n.then(response => response.json())\n.then(data => {\n  if (data.success) {\n    console.log("加密数据A:", data.encrypted_a);\n    console.log("加密数据B:", data.encrypted_b);\n  }\n});',
    parameters: [
      {
        name: 'session_id',
        type: 'string',
        description: '会话ID，由create_session接口返回'
      },
      {
        name: 'value_a',
        type: 'integer',
        description: '要加密的第一个整数值'
      },
      {
        name: 'value_b',
        type: 'integer',
        description: '要加密的第二个整数值'
      }
    ],
    returnType: 'JSON对象',
    returnDescription: '包含success状态和加密后的数据（截断显示）',
    notes: [
      '加密数据存储在服务器端的会话中',
      '返回的加密数据仅用于显示，实际计算使用服务器存储的完整加密数据',
      'BFV方案仅支持整数运算'
    ]
  },
  {
    id: 'compute',
    name: 'compute',
    description: '在加密数据上执行同态操作，如比较、加法或平均值计算。',
    example: 'fetch("http://localhost:5000/api/compute", {\n  method: "POST",\n  headers: {\n    "Content-Type": "application/json"\n  },\n  body: JSON.stringify({\n    session_id: "your_session_id",\n    operation: "add"  // 可选值: "compare", "add", "average"\n  })\n})\n.then(response => response.json())\n.then(data => {\n  if (data.success) {\n    console.log("结果类型:", data.result_type);\n    console.log("计算结果:", data.result);\n    console.log("说明:", data.explanation);\n  }\n});',
    parameters: [
      {
        name: 'session_id',
        type: 'string',
        description: '会话ID'
      },
      {
        name: 'operation',
        type: 'string',
        description: '要执行的操作，可选值："compare"（比较），"add"（加法），"average"（平均值）'
      }
    ],
    returnType: 'JSON对象',
    returnDescription: '包含success状态、结果类型、计算结果和说明',
    notes: [
      '比较操作是模拟的，因为全同态加密不直接支持比较',
      '加法操作在密文上直接执行',
      '平均值操作需要先解密求和结果，再计算平均值'
    ]
  },
  {
    id: 'verify',
    name: 'verify',
    description: '验证加密计算的结果，通过在明文上执行相同的操作并比较结果。',
    example: 'fetch("http://localhost:5000/api/verify", {\n  method: "POST",\n  headers: {\n    "Content-Type": "application/json"\n  },\n  body: JSON.stringify({\n    session_id: "your_session_id",\n    operation: "add"  // 与compute操作相同\n  })\n})\n.then(response => response.json())\n.then(data => {\n  if (data.success) {\n    console.log("明文结果:", data.plaintext_result);\n    console.log("结果匹配:", data.match);\n  }\n});',
    parameters: [
      {
        name: 'session_id',
        type: 'string',
        description: '会话ID'
      },
      {
        name: 'operation',
        type: 'string',
        description: '要验证的操作，与compute接口使用的操作相同'
      }
    ],
    returnType: 'JSON对象',
    returnDescription: '包含success状态、明文计算结果和匹配状态',
    notes: [
      '验证通过在明文上执行相同的操作并比较结果',
      '在实际应用中，验证步骤通常由不同的参与方执行',
      '这个接口主要用于演示目的'
    ]
  }
];

// 搜索和过滤
const searchQuery = ref('');
const filteredApiList = computed(() => {
  if (!searchQuery.value) return apiList;
  const query = searchQuery.value.toLowerCase();
  return apiList.filter(api => 
    api.name.toLowerCase().includes(query) || 
    api.description.toLowerCase().includes(query)
  );
});

function filterApiList() {
  // 搜索逻辑已通过计算属性实现
}

// 活动部分跟踪
const activeSection = ref('getting-started');
const activeApi = ref(null);
const docsContent = ref(null);

// 滚动到指定部分
function scrollToSection(sectionId) {
  const element = document.getElementById(sectionId);
  if (element && docsContent.value) {
    // 计算目标元素相对于 docs-content 的偏移
    const contentRect = docsContent.value.getBoundingClientRect();
    const elemRect = element.getBoundingClientRect();
    const offset = elemRect.top - contentRect.top + docsContent.value.scrollTop - 16; // 16px 适当偏移
    docsContent.value.scrollTo({ top: offset, behavior: 'smooth' });
    activeSection.value = sectionId;
    // 如果是API部分，显示右侧参数面板
    const api = apiList.find(a => a.id === sectionId);
    if (api) {
      activeApi.value = api;
    }
  }
}

// 处理滚动事件，更新活动部分
function handleScroll() {
  if (!docsContent.value) return;
  
  const sections = docsContent.value.querySelectorAll('.content-section');
  const scrollPosition = docsContent.value.scrollTop + 100; // 添加偏移量
  
  for (const section of sections) {
    const sectionTop = section.offsetTop;
    const sectionBottom = sectionTop + section.offsetHeight;
    
    if (scrollPosition >= sectionTop && scrollPosition < sectionBottom) {
      activeSection.value = section.id;
      break;
    }
  }
}

onMounted(() => {
  // 初始滚动到顶部
  if (docsContent.value) {
    docsContent.value.scrollTop = 0;
  }
  
  // 添加滚动监听
  handleScroll();
});
</script>

<style scoped>
.api-docs-view {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem 1rem;
}

.page-title {
  text-align: center;
  margin-bottom: 1rem;
}

.page-description {
  text-align: center;
  max-width: 800px;
  margin: 0 auto 3rem;
  color: var(--text-secondary);
}

/* 文档容器布局 */
.docs-container {
  display: grid;
  grid-template-columns: 250px 1fr 300px;
  gap: 2rem;
  height: calc(100vh - 200px);
  min-height: 600px;
}

/* 侧边栏样式 */
.docs-sidebar {
  background-color: var(--card-bg);
  border-radius: 8px;
  padding: 1.5rem;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow-y: auto;
  position: sticky;
  top: 90px;
  height: calc(100vh - 200px);
}

.search-box {
  margin-bottom: 1.5rem;
}

.search-box input {
  width: 100%;
  padding: 0.75rem;
  border-radius: 4px;
  border: 1px solid var(--border-color);
  background-color: var(--bg-color);
  color: var(--text-color);
}

.sidebar-section {
  margin-bottom: 1.5rem;
}

.section-title {
  font-weight: 700;
  margin-bottom: 0.75rem;
  color: var(--text-secondary);
  font-size: 0.9rem;
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

.section-links {
  list-style: none;
  padding: 0;
  margin: 0;
}

.section-links li {
  margin-bottom: 0.5rem;
}

.section-links a {
  display: block;
  padding: 0.5rem;
  border-radius: 4px;
  color: var(--text-color);
  text-decoration: none;
  transition: background-color 0.2s, color 0.2s;
}

.section-links a:hover {
  background-color: var(--hover-bg);
  color: var(--primary-color);
}

.section-links a.active {
  background-color: var(--primary-color);
  color: white;
}

/* 内容区样式 */
.docs-content {
  overflow-y: auto;
  padding-right: 1rem;
  height: calc(100vh - 200px);
  width: 750px;
}

.content-section {
  margin-bottom: 3rem;
  scroll-margin-top: 2rem;
}

.content-section h2 {
  margin-bottom: 1.5rem;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid var(--border-color);
}

/* 快速开始部分样式 */
.steps-container {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  margin-top: 2rem;
}

.step-item {
  display: flex;
  gap: 1rem;
  background-color: var(--card-bg);
  padding: 1.5rem;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.step-number {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: var(--primary-color);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  flex-shrink: 0;
}

.step-content {
  flex: 1;
}

.step-content h3 {
  margin-top: 0;
  margin-bottom: 0.5rem;
}

.step-content pre {
  margin-top: 1rem;
  background-color: var(--footer-bg);
  padding: 1rem;
  border-radius: 4px;
  overflow-x: auto;
}

/* 安装选项样式 */
.installation-options {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.install-card {
  background-color: var(--card-bg);
  padding: 1.5rem;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.install-card h3 {
  margin-top: 0;
  margin-bottom: 1rem;
}

.system-requirements {
  background-color: var(--footer-bg);
  padding: 1.5rem;
  border-radius: 8px;
  margin-top: 2rem;
}

.system-requirements h3 {
  margin-top: 0;
  margin-bottom: 1rem;
}

.system-requirements ul {
  padding-left: 1.5rem;
  margin-bottom: 1rem;
}

/* 基本概念样式 */
.concept-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.concept-card {
  background-color: var(--card-bg);
  padding: 1.5rem;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.concept-card h3 {
  margin-top: 0;
  margin-bottom: 1rem;
  color: var(--primary-color);
}

.concept-diagram {
  background-color: var(--footer-bg);
  padding: 1.5rem;
  border-radius: 8px;
  text-align: center;
  margin-top: 2rem;
}

.architecture-diagram {
  max-width: 100%;
  height: auto;
  margin: 1.5rem 0;
}

.diagram-caption {
  font-style: italic;
  color: var(--text-secondary);
}

/* API参考样式 */
.api-reference {
  background-color: var(--card-bg);
  padding: 2rem;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 2rem;
}

.api-details {
  margin-top: 1.5rem;
}

.code-example {
  margin-bottom: 2rem;
}

.code-example pre {
  background-color: var(--footer-bg);
  padding: 1.5rem;
  border-radius: 6px;
  overflow-x: auto;
  font-family: 'Roboto Mono', monospace;
  font-size: 0.9rem;
}

.parameters-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 2rem;
}

.parameters-table th,
.parameters-table td {
  padding: 0.75rem;
  text-align: left;
  border-bottom: 1px solid var(--border-color);
}

.parameters-table th {
  font-weight: 700;
  background-color: var(--footer-bg);
}

.return-value {
  margin-bottom: 2rem;
}

.notes-section ul {
  padding-left: 1.5rem;
}

.notes-section li {
  margin-bottom: 0.5rem;
}

/* 示例代码部分样式 */
.example-description {
  margin-bottom: 1.5rem;
}

.example-notes {
  background-color: var(--footer-bg);
  padding: 1.5rem;
  border-radius: 6px;
  margin-top: 1.5rem;
}

.example-notes h3 {
  margin-top: 0;
  margin-bottom: 1rem;
}

/* 参数面板样式 */
.docs-params {
  background-color: var(--card-bg);
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow-y: auto;
  position: sticky;
  top: 90px;
  height: calc(100vh - 200px);
}

.params-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  background-color: var(--primary-color);
  color: white;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

.params-header h3 {
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  color: white;
  font-size: 1.5rem;
  cursor: pointer;
}

.params-content {
  padding: 1.5rem;
}

.param-description {
  margin-bottom: 1.5rem;
  padding-bottom: 1.5rem;
  border-bottom: 1px solid var(--border-color);
}

.param-details {
  margin-bottom: 1.5rem;
  padding-bottom: 1.5rem;
  border-bottom: 1px solid var(--border-color);
}

.param-name {
  font-weight: 700;
  margin-bottom: 0.5rem;
}

.param-type {
  color: var(--primary-color);
  font-size: 0.9rem;
  margin-bottom: 0.5rem;
}

.param-info {
  font-size: 0.95rem;
}

.param-notes {
  background-color: var(--footer-bg);
  padding: 1rem;
  border-radius: 6px;
}

.param-notes h4 {
  margin-top: 0;
  margin-bottom: 0.75rem;
}

.param-notes ul {
  padding-left: 1.5rem;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .docs-container {
    grid-template-columns: 220px 1fr;
  }
  
  .docs-params {
    display: none;
  }
  
  .api-reference {
    padding: 1.5rem;
  }
}

@media (max-width: 768px) {
  .docs-container {
    grid-template-columns: 1fr;
    height: auto;
  }
  
  .docs-sidebar {
    position: static;
    height: auto;
    max-height: 300px;
  }
  
  .docs-content {
    height: auto;
    max-height: none;
    padding-right: 0;
  }
  
  .installation-options,
  .concept-grid {
    grid-template-columns: 1fr;
  }
  
  .step-item {
    flex-direction: column;
  }
  
  .step-number {
    margin-bottom: 1rem;
  }
}
</style>